package com.shanjupay.common.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * @author whb
 * @create 2021-11-30 11:03
 * @desciption 七牛云存储服务工具类
 */
public class QiniuUtils {
    private static final Logger LOGGER= LoggerFactory.getLogger(QiniuUtils.class);


    /**
     * 测试文件上传到七牛云存储服务
     */
    public static void testUpload2Qiniu() {
        //构造一个带指定 Region 对象的配置类，指定存储区域，和存储空间选择的区域一致
        Configuration configuration = new Configuration(Region.huanan());

        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(configuration);

        //...生成上传凭证，然后准备上传
        String accessKey = "xfATT5uFrVkgOqPazeI4nQAXX7vCO4TQq-ln6Kit";
        String secretKey = "hg59CUhQISPRU5xS0Zw6z83hUuQQVWoJ06n0-vN5";
        String bucket = "shanjupay-zz";

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = UUID.randomUUID().toString() + ".jpg";

        FileInputStream fileInputStream = null;

        String filePath = "C:\\Users\\Administrator\\Desktop\\1\\src=http___img.zcool.cn_community_01ce9c5e835487a80120a8956349f4.jpg@1280w_1l_2o_100sh.jpg&refer=http___img.zcool.jpg";
        try {
            fileInputStream = new FileInputStream(new File(filePath));
            //得到本地文件的字节数组
            //byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            byte[] bytes = IOUtils.toByteArray(fileInputStream);

            //认证
            Auth auth = Auth.create(accessKey, secretKey);
            //认证通过后得到token（令牌）
            String upToken = auth.uploadToken(bucket);

            try {
                //上传文件,参数：字节数组，key，token令牌
                //key: 建议我们自已生成一个不重复的名称
                Response response = uploadManager.put(bytes, key, upToken);
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试从七牛云上获取文件访问地址
     * @throws UnsupportedEncodingException
     */
    public static void testGetFileUrl() throws UnsupportedEncodingException {
        String fileName = "bfb58098-7900-4108-b067-49a779ea9192.jpg";
        String domainOfBucket = "http://r3btwgyp4.hn-bkt.clouddn.com";
        String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        String accessKey = "xfATT5uFrVkgOqPazeI4nQAXX7vCO4TQq-ln6Kit";
        String secretKey = "hg59CUhQISPRU5xS0Zw6z83hUuQQVWoJ06n0-vN5";
        Auth auth = Auth.create(accessKey, secretKey);
        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        System.out.println(finalUrl);
    }

    /**
     * 文件上传（七牛云）
     * @param accessKey
     * @param secretKey
     * @param bucket 存储空间明名称
     * @param bytes 上传文件的字节数组
     * @param fileName 外部传进来，七牛云上的文件名称和此保持一致
     */
    public static void upload2qiniu(String accessKey,String secretKey,String bucket, byte[] bytes,String fileName) throws RuntimeException{
        //构造一个带指定 Region 对象的配置类，指定存储区域，和存储空间选择的区域一致
        Configuration configuration = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(configuration);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        try {
            //认证
            Auth auth = Auth.create(accessKey, secretKey);
            //认证通过后得到token（令牌）
            String upToken = auth.uploadToken(bucket);
            try {
                //上传文件,参数：字节数组，key，token令牌
                //key: 建议我们自已生成一个不重复的名称
                Response response = uploadManager.put(bytes, key, upToken);
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                LOGGER.error("上传文件到七牛云：{}", ex.getMessage());
                try {
                    //System.err.println(r.bodyString());
                    LOGGER.error(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
                throw new RuntimeException(r.bodyString());
            }
        } catch (Exception e) {
            LOGGER.error("上传文件到七牛云：{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 类内测试：main方法
     * @param args
     */
    public static void main(String[] args) throws UnsupportedEncodingException {
        //测试文件上传
        //QiniuUtils.testUpload2Qiniu();

        //测试获取七牛云存储文件的访问地址
        QiniuUtils.testGetFileUrl();
    }
}
